package com.cn.aam.checaiduo.ui.homepage.fragment;

import android.graphics.Color;
import android.os.Bundle;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;

import com.cn.aam.checaiduo.AppData;
import com.cn.aam.checaiduo.Const;
import com.cn.aam.checaiduo.R;
import com.cn.aam.checaiduo.backend.RetrofitHome;
import com.cn.aam.checaiduo.backend.observer.OnRequestListener;
import com.cn.aam.checaiduo.backend.observer.OnRequestV2Listener;
import com.cn.aam.checaiduo.backend.rx.RxSchedulers;
import com.cn.aam.checaiduo.base.BaseFragment;
import com.cn.aam.checaiduo.base.ToolBarManager;
import com.cn.aam.checaiduo.base.adapter.layoutmanager.FullyGridLayoutManager;
import com.cn.aam.checaiduo.base.web.NormalWebActivity;
import com.cn.aam.checaiduo.bean.UserB;
import com.cn.aam.checaiduo.bean.base.NormalResponseB;
import com.cn.aam.checaiduo.bean.me.MeFinanceB;
import com.cn.aam.checaiduo.bean.me.PointMallB;
import com.cn.aam.checaiduo.bean.me.RedirectContentB;
import com.cn.aam.checaiduo.center.SharePreferenceCenter;
import com.cn.aam.checaiduo.center.UserCenter;
import com.cn.aam.checaiduo.ui.arouter.UIRouter;
import com.cn.aam.checaiduo.ui.arouter.section.RouterMore;
import com.cn.aam.checaiduo.ui.homepage.adapter.MeTypeAdapter;
import com.cn.aam.checaiduo.ui.me.AutoReservationActivity;
import com.cn.aam.checaiduo.ui.me.FinancialVoucherActivity;
import com.cn.aam.checaiduo.ui.me.InvestRecordActivity;
import com.cn.aam.checaiduo.ui.me.MessageListActivity;
import com.cn.aam.checaiduo.ui.me.PlatformIntroduceActivity;
import com.cn.aam.checaiduo.ui.me.RechargeWithDrawHomeActivity;
import com.cn.aam.checaiduo.utils.MyViewsUtils;
import com.cn.aam.checaiduo.utils.StringUtil;
import com.cn.aam.checaiduo.widget.WMToast;
import com.cn.aam.checaiduo.widget.WaveHelper;
import com.gelitenight.waveview.library.WaveView;

import butterknife.BindView;
import butterknife.OnClick;

/**
 * monker on 2017/5/19.
 */

public class MeFragment extends BaseFragment {

    @BindView(R.id.me_iv_canSeeMoney)
    ImageView mIvSeeMoney;
    @BindView(R.id.tv_totalAssets)
    TextView tvTotalAssets;
    @BindView(R.id.me_tv_investFunds)
    TextView mTvInvestFunds;
    @BindView(R.id.me_tv_reserveFunds)
    TextView mTvReserveFunds;
    @BindView(R.id.me_tv_accountBalance)
    TextView mTvAccountBalance;
    //View
    private WaveHelper mWaveHelper;
    @BindView(R.id.wave)
    WaveView waveView;

    @BindView(R.id.me_recyclerView)
    RecyclerView mRecyclerView;

    private MeFinanceB meFinanceB;
    private MeTypeAdapter adapter;

    private boolean isRequesting;//是否正在请求数据
    String totalAssets;
    String investing;
    String appoint_amount;
    String available_amount;


    public static MeFragment newInstance() {
        MeFragment intance = new MeFragment();
        return intance;
    }

    @Override
    protected int getLayoutId() {
        return R.layout.fragment_me;
    }


    @Override
    protected void initView(View view, Bundle savedInstanceState) {
        initTitle(false);
        initWaweView();
        initRecycler();
    }

    private void initTitle(boolean hasDot) {
        ToolBarManager.with(mActivity, WMContent)
                .setTitle("我的钱包")
                .setMenuTextContent("消息", hasDot)
                .setMenuTextClick(new ToolBarManager.OnMenuTextClickListener() {
                    @Override
                    public void onMenuTextClick() {
                        if (MyViewsUtils.isFastDoubleClick()) return;
                        startActivity(MessageListActivity.newInstance(mActivity));
                    }
                });
    }


    private void initData() {
        if (!hasLogin()) {
            return;
        }
        isRequesting = true;
        RetrofitHome.getInstance()
                .getInternalApi()
                .appFinance(AppData.getToken())
                .compose(RxSchedulers.<NormalResponseB<MeFinanceB>>toMain())
                .subscribe(new OnRequestV2Listener<MeFinanceB>(mActivity) {
                    @Override
                    protected boolean isShowProgressBar() {
                        return false;
                    }

                    @Override
                    public void onNext(NormalResponseB<MeFinanceB> value) {

                        super.onNext(value);
                        if (Const.STATE_LOGIN != value.getIsLogged()) {
                            goLogin();
                            return;
                        }
                        totalAssets = "0";
                        investing = "0";
                        appoint_amount = "0";
                        available_amount = "0";

                        meFinanceB = value.getData();
                        UserB userB = UserCenter.getInstance().getUser();
                        userB.setBank_cardno(meFinanceB.getBank_cardno());
                        userB.setBank_name(meFinanceB.getBank_name());
                        userB.setBank_limit(meFinanceB.getBank_limit());
                        UserCenter.getInstance().setUser(userB);


                        showMessageNotift(meFinanceB.getNew_notify());
                        if (SharePreferenceCenter.getInstance().isFinanceVisibility()) {
                            mIvSeeMoney.setImageResource(R.drawable.ic_eye_open);


                            if (meFinanceB.getTotal_asset() > 0)
                                totalAssets = StringUtil.dealDataEnd(meFinanceB.getTotal_asset() + "");
                            if (Float.parseFloat(meFinanceB.getInvesting()) > 0) {
                                investing = StringUtil.dealDataEnd(meFinanceB.getInvesting());
                            }

                            if (Float.parseFloat(meFinanceB.getAppoint_amount()) > 0) {
                                appoint_amount = StringUtil.dealDataEnd(meFinanceB.getAppoint_amount());
                            }
                            if (meFinanceB.getAvailable_amount() > 0) {
                                available_amount = StringUtil.dealDataEnd(meFinanceB.getAvailable_amount() + "");
                            }

                            tvTotalAssets.setText(totalAssets);//总资产
                            mTvInvestFunds.setText(investing);//在投
                            mTvReserveFunds.setText(appoint_amount);//预约
                            mTvAccountBalance.setText(available_amount);//余额
                        } else {
                            mIvSeeMoney.setImageResource(R.drawable.ic_eye_close);
                            tvTotalAssets.setText("****");//总资产
                            mTvInvestFunds.setText("****");//在投
                            mTvReserveFunds.setText("****");//预约
                            mTvAccountBalance.setText("****");//余额
                        }
                        //操作完成后 更改状态
                        isRequesting = false;
                    }
                });
    }


    private void initRecycler() {
        adapter = new MeTypeAdapter(mActivity);
        FullyGridLayoutManager layoutManager = new FullyGridLayoutManager(mActivity, 3);
        mRecyclerView.setLayoutManager(layoutManager);
        mRecyclerView.setAdapter(adapter);
        adapter.setDataList(adapter.getDataList());
        adapter.setOnItemClickListener(new MeTypeAdapter.OnItemClick() {
            @Override
            public void onClick(int position) {
                if (MyViewsUtils.isFastDoubleClick()) return;
                dealClick(position);
            }
        });

    }

    private void dealClick(int position) {
        if (isRequesting) return;
        switch (position) {
            case 0://充值提现
                startActivity(RechargeWithDrawHomeActivity.newInstance(mActivity, available_amount));
                break;
            case 1://预约投资
                startActivity(AutoReservationActivity.newInstance(mActivity));
                break;
            case 2://理财券->代金券
                startActivity(FinancialVoucherActivity.newInstance(mActivity));
                break;
            case 3://新浪钱包
                String authStatus = UserCenter.getInstance().getUser().getAuth_status();
                if (!TextUtils.equals(authStatus, Const.AUTH_STATUS)) {
                    WMToast.normal("请先进行实名认证");
                    UIRouter.getInstance().openPage(mActivity, UIRouter.MORE.AUTH);
                    return;
                }
                gotoSiNaWallet();
//                startActivity(NormalWebActivity.newInstance(mActivity, BuildConfig.HOST + "Wap/Usercenter/wallet", "新浪钱包"));
                break;
            case 4://邀请有奖
                UIRouter.getInstance().openPage(mActivity, UIRouter.ME.AC_INVITEPRIZES);
                break;
            case 5://投资记录
                startActivity(InvestRecordActivity.newInstance(mActivity));
                break;
            case 6://积分
                gotoPointMall();
                break;
            case 7://活动中心
                startActivity(PlatformIntroduceActivity.newInstance(mActivity, PlatformIntroduceActivity.FLAG_ACTIVITY));
                break;
            case 8://签到
                UIRouter.getInstance().openPage(mActivity, UIRouter.ME.AC_SIGNIN);
                break;
        }
    }


    /**
     * 初始化WaveView
     */
    private void initWaweView() {
        waveView.setShapeType(WaveView.ShapeType.SQUARE);
        waveView.setAmplitudeRatio(0.1f);
        waveView.setWaveShiftRatio(0.4f);
        waveView.setWaterLevelRatio(0.4f);
//        waveView.setWaveLengthRatio();
        waveView.setWaveColor(Color.argb(10, 255, 255, 255), Color.argb(15, 255, 255, 255));
        mWaveHelper = new WaveHelper(waveView);
    }

    @OnClick(R.id.me_iv_canSeeMoney)
    void clicksetCanSeeMoney() {
        boolean canSeeMoney = SharePreferenceCenter.getInstance().isFinanceVisibility();
        if (canSeeMoney) {
            SharePreferenceCenter.getInstance().setFinanceVisibility(false);
            mIvSeeMoney.setImageResource(R.drawable.ic_eye_close);
            tvTotalAssets.setText("****");
            tvTotalAssets.setText("****");//总资产
            mTvInvestFunds.setText("****");//在投
            mTvReserveFunds.setText("****");//预约
            mTvAccountBalance.setText("****");//余额
        } else {
            SharePreferenceCenter.getInstance().setFinanceVisibility(true);
            mIvSeeMoney.setImageResource(R.drawable.ic_eye_open);
            tvTotalAssets.setText(totalAssets);//总资产
            mTvInvestFunds.setText(investing);//在投
            mTvReserveFunds.setText(appoint_amount);//预约
            mTvAccountBalance.setText(available_amount);//余额
        }
    }

    @Override
    public void onHiddenChanged(boolean hidden) {
        super.onHiddenChanged(hidden);
        if (!isRequesting && !hidden) {
            initData();
        } else {
            isRequesting = false;
        }
    }

    @Override
    public void onResume() {
        super.onResume();
        if (!isRequesting) {
            initData();
        }
        mWaveHelper.start();
    }

    @Override
    public void onPause() {
        super.onPause();
        mWaveHelper.cancel();
    }

    /**
     * 时间：2017/6/15
     * 描述：我的钱包
     */
    private void gotoSiNaWallet() {
        RetrofitHome.getInstance()
                .getInternalApi()
                .getWallet(AppData.getToken())
                .compose(RxSchedulers.<RedirectContentB>toMain())
                .subscribe(new OnRequestListener<RedirectContentB>(mActivity) {
                    @Override
                    protected boolean isShowProgressBar() {
                        return false;
                    }

                    @Override
                    public void onNext(RedirectContentB value) {
                        super.onNext(value);
                        if (value.getRedirect_content() != null) {
                            startActivity(NormalWebActivity.newInstance(mActivity, value.getRedirect_content(), "我的存钱罐", "MEFRAGMENT"));
                        }
                    }
                });
    }

    /**
     * 时间：2017/6/15
     * 描述：商城
     */
    private void gotoPointMall() {
        RetrofitHome.getInstance()
                .getInternalApi()
                .pointMall(AppData.getToken())
                .compose(RxSchedulers.<PointMallB>toMain())
                .subscribe(new OnRequestListener<PointMallB>(mActivity) {
                    @Override
                    protected boolean isShowProgressBar() {
                        return false;
                    }

                    @Override
                    public void onNext(PointMallB value) {
                        super.onNext(value);
                        if (value != null)
                            startActivity(NormalWebActivity.newInstance(mActivity, value.getUrl(), "我的积分"));
                    }
                });
    }

    /**
     * 时间：2017/6/26
     * 描述：是否有新消息
     */
    private void showMessageNotift(String notify) {
        initTitle(!TextUtils.equals(notify, "0"));
    }

}
